﻿using System;
using System.Collections.Generic;
using Windows.ApplicationModel;
using Windows.ApplicationModel.Activation;
using Windows.Storage;
using Windows.System;
using Windows.UI.ApplicationSettings;
using Windows.UI.Popups;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media;
using Services.ViewModel;
using Books.SQLite;
using AudioBooks.Data;
using AudioBooks.SQLite;
// The Blank Application template is documented at http://go.microsoft.com/fwlink/?LinkId=234227

namespace AudioBooks
{
      
    /// <summary>
    /// Provides application-specific behavior to supplement the default Application class.
    /// </summary>
    sealed partial class App : Application
    {
        private static MediaElement player;

        public static IWebServices CallService;
        public static string BookIdSelect = string.Empty;
        public static string NowPlayTitle = "";
        public static string NowPlayBookId = "";
        public static string NowPlayChapterId = "";

        public static string ImageLink = "";

        public static IReadOnlyList<StorageFile> GlobalPlaylist;
        public static int PlayIndex;

        public static string DatabasePath { get; set; }

        public static MediaElement Player
        {
            get {
                if (player == null)
                {
                    DependencyObject rootGrid = VisualTreeHelper.GetChild(Window.Current.Content, 0);
                    player = (MediaElement)VisualTreeHelper.GetChild(rootGrid, 0);
                }
                return player; 
            }
            set { player = value; }
        }

        /// <summary>
        /// Initializes the singleton application object.  This is the first line of authored code
        /// executed, and as such is the logical equivalent of main() or WinMain().
        /// </summary>
        public App()
        {
            this.InitializeComponent();
            this.Suspending += OnSuspending;
            CallService = new WebServices(new Uri("http://zozoapp.com/api/", UriKind.Absolute));
        }

        /// <summary>
        /// Invoked when the application is launched normally by the end user.  Other entry points
        /// will be used when the application is launched to open a specific file, to display
        /// search results, and so forth.
        /// </summary>
        /// <param name="args">Details about the launch request and process.</param>
        protected override void OnLaunched(LaunchActivatedEventArgs args)
        {
            Frame rootFrame = Window.Current.Content as Frame;
            DatabasePath = Windows.Storage.ApplicationData.Current.LocalFolder.Path + "\\book.sqllite";
            ISQLManagerment sql = new SQLManagerment(DatabasePath);
            sql.Initialize();
            // Do not repeat app initialization when the Window already has content,
            // just ensure that the window is active
            if (rootFrame == null)
            {
                SettingsPane.GetForCurrentView().CommandsRequested += DownloadManagerGroup_CommandsRequested;

                // Create a Frame to act as the navigation context and navigate to the first page
                rootFrame = new Frame();
                rootFrame.Style = Resources["RootFrameStyle"] as Style;
                if (args.PreviousExecutionState == ApplicationExecutionState.Terminated)
                {
                    //TODO: Load state from previously suspended application
                }

                // Place the frame in the current Window
                Window.Current.Content = rootFrame;
            }

            if (rootFrame.Content == null)
            {
                // When the navigation stack isn't restored navigate to the first page,
                // configuring the new page by passing required information as a navigation
                // parameter
                if (!rootFrame.Navigate(typeof(Main), args.Arguments))
                {
                    throw new Exception("Failed to create initial page");
                }
            }
            if (!String.IsNullOrEmpty(args.Arguments))
            {

                rootFrame.Navigate(typeof(Main), args.Arguments);
                Window.Current.Content = rootFrame;
                Window.Current.Activate();
                return;
            }
            // Ensure the current window is active
            Window.Current.Activate();
        }

        void DownloadManagerGroup_CommandsRequested(SettingsPane sender, SettingsPaneCommandsRequestedEventArgs eventArgs)
        {
            UICommandInvokedHandler handler = new UICommandInvokedHandler(onDowloadManagerCommand);
            UICommandInvokedHandler privacyHandler = new UICommandInvokedHandler(onPrivacyCommand);

            SettingsCommand generalCommand = new SettingsCommand("downloadManager", "Download Manager", handler);
            SettingsCommand privacyCommand = new SettingsCommand("privacyPolicy", "Privacy Policy", privacyHandler);
            //eventArgs.Request.ApplicationCommands.Add(generalCommand);
            eventArgs.Request.ApplicationCommands.Add(privacyCommand);
        }

        private void onDowloadManagerCommand(IUICommand command)
        {
            Frame rootFrame = Window.Current.Content as Frame;

            //Launcher.LaunchUriAsync(new Uri("http://sdrv.ms/QDphhL"));
           // rootFrame.Navigate(typeof(DownloadManagerGroup.DownloadManager));
        }

        private void onPrivacyCommand(IUICommand command)
        {
            Launcher.LaunchUriAsync(new Uri("http://zozoapp.info/privacy-win8.htm"));
        }

        /// <summary>
        /// Invoked when application execution is being suspended.  Application state is saved
        /// without knowing whether the application will be terminated or resumed with the contents
        /// of memory still intact.
        /// </summary>
        /// <param name="sender">The source of the suspend request.</param>
        /// <param name="e">Details about the suspend request.</param>
        private void OnSuspending(object sender, SuspendingEventArgs e)
        {
            var deferral = e.SuspendingOperation.GetDeferral();
            //TODO: Save application state and stop any background activity
            if (player.PlayToSource != null)
            {
                var BookMark = new PlayChapterInfo()
                {
                    BookId = App.NowPlayBookId,
                    Position = App.Player.Position,
                    ChapterName = App.NowPlayChapterId,
                    ImagePath = App.ImageLink,
                    BookName = App.NowPlayTitle
                };
                HandlePlayChapter.SaveDataPlayChapterInfo(BookMark);
            }
          
            deferral.Complete();
        }

      
    }
}
